/**
Date: 2025-08-13
Copyright (c) 2025 CAX Conversion Project
*/
import * as XLSX from 'xlsx'
 
export const file2Preview = (file: File) => {
  return new Promise(function (resolve) {
    const reader = new FileReader();// 文件加载事件
    reader.onload = function (e) {
      const data = e.target?.result;
      const workbook = XLSX.read(data, {
        type: "binary", cellDates: true,
      });
      // 拿第-个sheet
      const worksheet = workbook.Sheets[workbook.SheetNames[0]];
      const html = XLSX.utils.sheet_to_html(worksheet);
      // 返回html
      resolve(html);
    };
    reader.readAsArrayBuffer(file);
  });
};

export const file2Data = (file: File)  => {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.onload = function (e) {
      const data = e.target?.result;
      if (!data) {
        reject(new Error("Failed to read file data"));
        return;
      }
 
      try {
        const workbook = XLSX.read(data, { type: "binary" });
        const result: any[] = [];
 
        workbook.SheetNames.forEach((sheetName) => {
          const sheet = workbook.Sheets[sheetName];
          const jsonData = XLSX.utils.sheet_to_json(sheet, { header: 1, raw: false });
          if (jsonData.length > 0) {
            result.push({
            sheetName,
            sheet: jsonData
          });
          }
          
        });
 
        console.log(result); // 输出解析后的数据
        resolve(result);
      } catch (error) {
        reject(error);
      }
    };
 
    reader.onerror = function (e) {
      reject(new Error("FileReader error: " + e.target?.error?.message));
    };
 
    reader.readAsBinaryString(file);
  });
};